#!/usr/bin/env php
<?php
$SOAR_DIR=getenv("SOAR_DIR");
if(empty($SOAR_DIR)) $SOAR_DIR="/opt/soar";
$SOAR_DIR="../../../../../..";
include "$SOAR_DIR/common/php/soar/soar.inc";

function usage($selfname)
{/*{{{*/
    print "Usage: $selfname host:port [command]\n";
}/*}}}*/

function call($sock, $cmd)
{/*{{{*/
    $p=strpos($cmd, " ");
    if($p === false)
        $c=$cmd;
    else
        $c=substr($cmd, $p);
    $c=strtoupper($c);
    if(in_array($c, array("EXIT","QUIT","BYE")))
        return "";
    $cmd.="\r\n";
    $res=socket_send($sock, $cmd, strlen($cmd), 0);
    if($res === false || $res == 0)
    {
        printf("send to server fail: %s\n", 
                socket_strerror(socket_last_error()));
        return "";
    }
    $res=socket_recv($sock, $respond, 2048, 0);
    if($res === false || $res == 0)
    {
        printf("recv from server fail: %s\n", 
                socket_strerror(socket_last_error()));
    }
    $respond=trim($respond);
    return $respond;
}/*}}}*/

function main($argv)
{/*{{{*/
    if(count($argv) < 2)
    {
        usage(basename($argv[0]));
        return 1;
    }

    $addr=$argv[1];
    $TIMEOUT=5;
    $sock=sock::connect($addr, $TIMEOUT);
    if($sock === false)
    {
        print "Connect to $addr\n";
        return 1;
    }

    if(empty($argv[2]))
    {
        $prompt=$addr."> ";
        while(1)
        {
            print $prompt;
            $cmd=fgets(STDIN);
            if($cmd === false) break;
            $cmd=trim($cmd);
            $respond=call($sock, $cmd);
            if(empty($respond)) break;
            print $respond."\n\n";
        }
    }
    else
    {
        $respond=call($sock, $argv[2]);
        print $respond."\n\n";
    }

    return 0;
}/*}}}*/

exit(main($argv));
?>
